package com.example.sunmiv1.adapter;

import android.annotation.SuppressLint;
import android.content.Context;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.method.DigitsKeyListener;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.example.sunmiv1.R;
import com.example.sunmiv1.activity.AddAllocationActivity;
import com.example.sunmiv1.entity.AllocationGoodsInfo;
import com.example.sunmiv1.utils.LogUtil;
import com.example.sunmiv1.utils.Tools;
import com.example.sunmiv1.utils.net.ACache;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

public class AddAllocationAdapter extends BaseAdapter {

    private Context context;
    private ViewHolder viewHolder;
    private List<AllocationGoodsInfo.DataBean> list;
    private static final String TAG = "AddAllocationAdapter";
    private String pricePermission;// 門店查看價格權限

    public AddAllocationAdapter(Context context, List<AllocationGoodsInfo.DataBean> list) {
        this.context = context;
        this.list = list;
        ACache aCache = ACache.get(context);
        pricePermission = aCache.getAsString("showPrice");
    }

    @Override
    public int getCount() {
        return list.size();
    }

    @Override
    public Object getItem(int position) {
        return list.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    private int select = 9999;

    public void setSelect(int select) {
        Log.d("測試6","成功");
        this.select = select;
//        list.clear();
//        list.add(list.get(select));
        notifyDataSetChanged();
        Log.d("測試7","成功");
    }

    @SuppressLint("SetTextI18n")
    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        convertView = View.inflate(context, R.layout.add_deposit_adapter, null);
        viewHolder = new ViewHolder(convertView);
        Log.d("測試6","成功");
        if (select == position) {
            Log.d("測試7","成功");
            convertView.setBackgroundResource(R.drawable.red_border);
        } else {
            convertView.setBackgroundResource(R.color.white);
        }
        if (AddAllocationActivity.opera) {
            viewHolder.addDepositCheck.setVisibility(View.VISIBLE);
        } else {
            viewHolder.addDepositCheck.setVisibility(View.GONE);
        }
        viewHolder.addDepositTvNum.setText(R.string.deposit_good_num);
        viewHolder.addDepositCheck.setOnCheckedChangeListener(null);
        viewHolder.addDepositCheck.setChecked(list.get(position).isChecked());
        viewHolder.addDepositCheck.setOnCheckedChangeListener((buttonView, isChecked) -> {
            list.get(position).setChecked(isChecked);
            notifyDataSetChanged();
        });
        if(TextUtils.isEmpty(list.get(position).getCompany())){
            ((View)viewHolder.addDepositUnit.getParent()).setVisibility(View.GONE);
        }else {
            ((View)viewHolder.addDepositUnit.getParent()).setVisibility(View.VISIBLE);
            viewHolder.addDepositUnit.setText(list.get(position).getCompany());
        }
        viewHolder.addDepositName.setText(list.get(position).getGoods_name());
        viewHolder.addDepositFreightNumber.setText(list.get(position).getGoods_number());
        viewHolder.addDepositCode.setText(list.get(position).getGoods_code());
        viewHolder.addDepositStock.setText(list.get(position).getGoods_num() + "");
        Tools.hideViewInItem(list.get(position).getSku_name(), viewHolder.infoSkuName);
        if ("2".equals(list.get(position).getPricing_method())) {//稱重商品
            viewHolder.addDepositNum.setKeyListener(DigitsKeyListener.getInstance("0123456789."));
        } else {
            viewHolder.addDepositNum.setKeyListener(DigitsKeyListener.getInstance("0123456789"));
        }

        viewHolder.addDepositPrice.setText(list.get(position).getStock_price() + "");
        final TextWatcher adpTextWatcher = new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                limitDecimal(s, viewHolder.addDepositPrice);
            }

            @Override
            public void afterTextChanged(Editable s) {
                if (viewHolder.addDepositPrice.hasFocus()) {
                    if (!TextUtils.isEmpty(s.toString().trim())) {
                        list.get(position).setStock_price(Double.parseDouble(s.toString().trim()));
                    } else {
                        list.get(position).setStock_price(0.0);
                    }

                }
            }
        };
        setETFocusChangeListener(position, adpTextWatcher, viewHolder.addDepositPrice);

        final EditText dpnET = viewHolder.addDepositNum;
        dpnET.setText(list.get(position).getOutput_num());
        LogUtil.i("getOutput_num():" + list.get(position).getOutput_num());
        final TextWatcher adnTextWatcher = new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
//                limitDecimal(s, viewHolder.addDepositNum);
            }

            @Override
            public void afterTextChanged(Editable s) {
                if (dpnET.hasFocus()) {
                    if (!TextUtils.isEmpty(s.toString().trim())) {
                        list.get(position).setOutput_num(s.toString().trim());
                        LogUtil.i("setOutput_num()1:" + s.toString().trim());
                    } else {
                        list.get(position).setOutput_num("");
                        LogUtil.i("setOutput_num()2:" + s.toString().trim());
                    }
                }
            }
        };
        setETFocusChangeListener(position, adnTextWatcher, dpnET);

        final EditText adrET = viewHolder.addDepositRemark;
        adrET.setText(list.get(position).getRemark());
        final TextWatcher adrTextWatcher = new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (adrET.hasFocus()) {
                    list.get(position).setRemark(s.toString().trim());
                }
            }
        };
        setETFocusChangeListener(position, adrTextWatcher, adrET);

        if ("2".equals(pricePermission)) {
            ((View) viewHolder.addDepositPrice.getParent()).setVisibility(View.GONE);
        }
        if ("1".equals(list.get(position).getSerial_number_state())) {
            viewHolder.inventorySearchAdapterChooseSerial.setVisibility(View.VISIBLE);
            viewHolder.addDepositNum.setVisibility(View.GONE);
            Log.e(TAG, "onBindViewHolder: 商品的庫存========"+list.get(position).getOutput_num() );
            if (TextUtils.isEmpty(list.get(position).getOutput_num())) {
                viewHolder.inventorySearchAdapterInventoryTv.setText("0");
            }else{
                viewHolder.inventorySearchAdapterInventoryTv.setText(list.get(position).getOutput_num());
            }
        } else {
            viewHolder.inventorySearchAdapterChooseSerial.setVisibility(View.GONE);
            viewHolder.addDepositNum.setVisibility(View.VISIBLE);
        }
        final int index = position;
        viewHolder.inventorySearchAdapterChoose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                choose.choose(index);
            }
        });
        return convertView;
    }


    private Choose choose;
    public void setChoose(Choose choose) {
        this.choose = choose;
    }

    public interface Choose {
        void choose(int index);
    }

    /**
     * 設置edittext焦點的監聽器
     *
     * @param position
     * @param textWatcher
     * @param editText
     */
    private void setETFocusChangeListener(int position, TextWatcher textWatcher, EditText editText) {
        editText.setOnFocusChangeListener((v, hasFocus) -> {
            if (hasFocus) {
                ((EditText) v).addTextChangedListener(textWatcher);
                Log.e("addTextChanged", position + "");
            } else {
                ((EditText) v).removeTextChangedListener(textWatcher);
                Log.e("removeTextChanged", position + "");
            }
        });
    }

    /**
     * 限制小數點後三位
     *
     * @param charSequence
     * @param num
     */
    private void limitDecimal(CharSequence charSequence, EditText num) {
        if (charSequence.toString().contains(".")) {
            if (-1 != charSequence.toString().indexOf(".", charSequence.toString().indexOf(".") + 1)) {
                num.setText(charSequence.toString().
                        substring(0, charSequence.toString().length() - 1));
                num.setSelection(charSequence.length() - 1);
            } else {
                if (charSequence.length() - 1 - charSequence.toString().indexOf(".") > 3) {
                    charSequence = charSequence.toString().subSequence(0, charSequence.toString().indexOf(".") + 4);
                    num.setText(charSequence);
                    num.setSelection(charSequence.length());
                }
            }
        }
        if (charSequence.toString().trim().substring(0).equals(".")) {
            charSequence = "0" + charSequence;
            num.setText(charSequence);
            num.setSelection(2);
        }

        if (charSequence.toString().startsWith("0") && charSequence.toString().trim().length() > 1) {
            if (!charSequence.toString().substring(1, 2).equals(".")) {
                num.setText(charSequence.subSequence(1, 2));
                num.setSelection(1);
            }
        }
    }

    static class ViewHolder {
        @BindView(R.id.addDeposit_check)
        CheckBox addDepositCheck;
        @BindView(R.id.addDeposit_name)
        TextView addDepositName;
        @BindView(R.id.info_sku_name)
        TextView infoSkuName;
        @BindView(R.id.layout_sku_name)
        RelativeLayout layoutSkuName;
        @BindView(R.id.addDeposit_freightNumber)
        TextView addDepositFreightNumber;
        @BindView(R.id.addDeposit_code)
        TextView addDepositCode;
        @BindView(R.id.addDeposit_tvStock)
        TextView addDepositTvStock;
        @BindView(R.id.addDeposit_stock)
        TextView addDepositStock;
        @BindView(R.id.addDeposit_tvUnit)
        TextView addDepositTvUnit;
        @BindView(R.id.addDeposit_unit)
        TextView addDepositUnit;
        @BindView(R.id.addDeposit_tvPrice)
        TextView addDepositTvPrice;
        @BindView(R.id.addDeposit_price)
        EditText addDepositPrice;
        @BindView(R.id.addDeposit_tvNum)
        TextView addDepositTvNum;
        @BindView(R.id.addDeposit_num)
        EditText addDepositNum;
        @BindView(R.id.addDeposit_remark)
        EditText addDepositRemark;
        @BindView(R.id.inventorySearch_adapter_chooseSerial)
        LinearLayout inventorySearchAdapterChooseSerial;
        @BindView(R.id.inventorySearch_adapter_choose)
        TextView inventorySearchAdapterChoose;
        @BindView(R.id.inventorySearch_adapter_inventoryTv)
        TextView inventorySearchAdapterInventoryTv;

        ViewHolder(View view) {
            ButterKnife.bind(this, view);
        }
    }
}
